import React, { MouseEventHandler, ReactNode, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import { CSSTransition } from 'react-transition-group';
import styles from './index.module.scss';

export interface PopupProps {
    open?: boolean;
    onClose?: MouseEventHandler<HTMLDivElement>;
    children?: ReactNode;
}

/**
 * 通用弹出窗口，自低而上弹出
 */
const Popup: React.FC<PopupProps> = (props) => {
    const { open, onClose, children } = props;

    const nodeRef = useRef(null);

    // 当弹窗打开时，禁止页面滚动
    useEffect(() => {
      if (open) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = 'auto';
      }

      return () => {
        document.body.style.overflow = 'auto';
      }
    }, [open])

    // 将弹窗渲染到 body 中
    return ReactDOM.createPortal(
        <CSSTransition
            in={open}
            timeout={300}
            classNames={{
              enter: styles['fade-enter'], // 进入动画的类名
              enterActive: styles['fade-enter-active'], // 进入动画激活的类名
              exit: styles['fade-exit'], // 退出动画的类名
              exitActive: styles['fade-exit-active'], // 退出动画激活的类名
            }}
            unmountOnExit
            nodeRef={nodeRef}
        >
            {/* 背景遮罩 */}
            <div ref={nodeRef} className={styles.overlay} onClick={onClose}>
                {/* 内容区 */}
                <div
                    className={styles.content}
                    onClick={(e) => e.stopPropagation()}
                >
                    {children}
                </div>
            </div>
        </CSSTransition>,
        document.body,
    );
};

export default Popup;
